package com.lagou.edu.zdy.rpc;

import com.lagou.edu.zdy.util.JSONSerializer;
import com.lagou.edu.zdy.util.RpcDecoder;
import com.lagou.edu.zdy.util.RpcEncoder;
import com.lagou.edu.zdy.util.RpcRequest;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

public class ServiceBootstrap {

    public static void main(String[] args){
        startServer("localhost",8990);
    }

    /**
     * 启动服务
     * @param serverName 服务名
     * @param port 端口号
     */
    public static void startServer(String serverName, int port) {

        try {
            NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(eventLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
//                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
//                            pipeline.addLast(new RpcEncoder(String.class, new JSONSerializer()));
                            pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                            pipeline.addLast(new UserServerHandler());
                        }
                    });

            serverBootstrap.bind(serverName, port).sync();
        }catch (InterruptedException e){
            e.printStackTrace();
        }

    }
}
